//
//  TJAuthController.m
//  Teleport
//
//  Created by xtjun on 2020/6/14.
//  Copyright © 2020 xtjun. All rights reserved.
//

#import "TJAuthController.h"

@interface TJAuthController ()<UIScrollViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (weak, nonatomic) UIView *mainContentView;
@property (weak, nonatomic) UIScrollView *mainView;
@property (weak, nonatomic) UITextField *nameTextField;
@property (weak, nonatomic) UITextField *IdCradTextField;
@property (weak, nonatomic) UIView *bottomView;
@property (weak, nonatomic) UIButton *commitButton;
/**正面 */
@property (copy, nonatomic) NSString *IdCardFile1Path;
/**反面 */
@property (copy, nonatomic) NSString *IdCardFile2Path;
/**护照 */
@property (copy, nonatomic) NSString *passportFilePath;
@property (assign, nonatomic) NSInteger imageTag;
@property (weak, nonatomic) UIImageView *currentImage;



@end

@implementation TJAuthController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addSubView];
    
}

- (void)addSubView {
    
    self.view.backgroundColor = UIColor_Hex(0xf2f2f2);
    
    CGFloat scrollViewH = KScreenHeight - TabbarSafeBottomMargin - KNavBarHight - 64;
    UIScrollView *placeholderView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, KNavBarHight, KScreenWidth, scrollViewH)];
    placeholderView.showsHorizontalScrollIndicator = NO;
    placeholderView.showsVerticalScrollIndicator = NO;
    placeholderView.bounces = NO;
    placeholderView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.view addSubview:placeholderView];
    CGSize contentSize = CGSizeMake(KScreenWidth, scrollViewH);
    placeholderView.contentSize = contentSize;
    
    UIScrollView *mainView = [[UIScrollView alloc] initWithFrame:placeholderView.bounds];
    mainView.showsHorizontalScrollIndicator = NO;
    mainView.showsVerticalScrollIndicator = NO;
    mainView.scrollEnabled = NO;
    mainView.bounces = NO;
    mainView.delegate = self;
    mainView.pagingEnabled = YES;
    mainView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    mainView.contentSize = contentSize;
    [placeholderView addSubview:mainView];
    
    UIView *mainContentView = [UIView tj_addToView:mainView];
    [mainContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
        make.width.offset(KScreenWidth);
        make.height.offset(scrollViewH);
    }];
    
    _mainView = mainView;
    _mainContentView = mainContentView;
    
    QMUITextField *nameTextField = [[QMUITextField alloc] init];
    nameTextField.textInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [nameTextField shearRoundedCornersWithRadiu:3];
    nameTextField.backgroundColor = UIColor.whiteColor;
    [mainContentView addSubview:nameTextField];
    nameTextField.placeholder = @"请输入您的姓名".localizedString;
    [nameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.top.offset(10);
        make.height.offset(40);
    }];
    
    QMUITextField *IdCradTextField = [[QMUITextField alloc] init];
    IdCradTextField.textInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [IdCradTextField shearRoundedCornersWithRadiu:3];
    IdCradTextField.keyboardType = UIKeyboardTypeASCIICapable;
    IdCradTextField.backgroundColor = UIColor.whiteColor;
    [mainContentView addSubview:IdCradTextField];
    IdCradTextField.placeholder = @"请输入证件号码".localizedString;
    [IdCradTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.equalTo(nameTextField);
        make.top.equalTo(nameTextField.mas_bottom).offset(10);
    }];
    
    [nameTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [IdCradTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    _IdCradTextField = IdCradTextField;
    _nameTextField = nameTextField;
    _mainContentView = mainContentView;
    
    _IdCradTextField.font = UIFont_Px(15);
    _nameTextField.font = UIFont_Px(15);
    
    if ([_type isEqualToString:@"IdCard"]) {//身份证
        [self addIdCardContentView];
    } else {
        [self addPassportContentView];
    }
    
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
    
    [self.mainContentView layoutIfNeeded];
    [self.mainContentView setNeedsLayout];
    
    contentSize = CGSizeMake(KScreenWidth, CGRectGetMaxY(self.bottomView.frame));
    self.mainView.contentSize = contentSize;
    [self.mainContentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.offset(contentSize.height);
    }];
    
    
    UIButton *commitButton = [UIButton buttonWithSuperView:self.view font:UIFont_Px(18) color:UIColor.whiteColor title:@"提交认证".localizedString];
    commitButton.backgroundColor = UIColor.tj_mainColor;
    [commitButton shearRoundedCornersWithRadiu:3];
    [commitButton addTarget:self action:@selector(didClickCommitButton) forControlEvents:UIControlEventTouchUpInside];
    [commitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-34);
        make.left.offset(34);
        make.height.offset(44);
        make.centerX.offset(0);
        make.bottom.offset(-TabbarSafeBottomMargin - 10);
    }];
    
    _commitButton = commitButton;
    
    [self textFieldDidChange: _nameTextField];
}


- (void)textFieldDidChange:(UITextField *)textField {
    _commitButton.userInteractionEnabled = (_nameTextField.text.replacingEmptyString.length && _IdCradTextField.text.replacingEmptyString.length) && ((_IdCardFile1Path.length && _IdCardFile2Path.length) || _passportFilePath.length) ;
    _commitButton.backgroundColor = (_commitButton.userInteractionEnabled) ? UIColor.tj_mainColor : [UIColor_Hex(0x666666) colorWithAlphaComponent:0.3];
}
/**提交认证 */
- (void)didClickCommitButton {
    
    NSMutableDictionary *parameters = @{
        @"userId": TJUserInfo.readInfo.userId,
        @"name": _nameTextField.text
    }.mutableCopy;
    NSString *url = @"";
    if ([_type isEqualToString:@"IdCard"]) {//身份证
        [parameters setObject:_IdCradTextField.text forKey:@"cardNo"];
        [parameters setObject:_IdCardFile1Path forKey:@"positiveFile"];
        [parameters setObject:_IdCardFile2Path forKey:@"sideFile"];
        url= @"member/member/setAuthenNew";
        
        
    } else {
        [parameters setObject:_IdCradTextField.text forKey:@"passportCard"];
        [parameters setObject:_passportFilePath forKey:@"passportPic"];
        url= @"member/member/setAuthenByPassport";
    }
    
    [self showloading];
    
    [TJNetworking.shareNetworking POSTNew:url parameters:parameters success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        
        [self hiddenloading];
        [self.navigationController popToRootViewControllerAnimated:YES];
    } failure:^(NSError * _Nonnull error) {
        [self hiddenloading];
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
    
}

- (void)addIdCardContentView {
    
    UIView *IdCardContentView = [UIView tj_addToView:_mainContentView];
    IdCardContentView.backgroundColor = UIColor_Hex(0xF5F5F5);

    UILabel *titleLabel = [UILabel lableWithSuperView:IdCardContentView font:UIFont_Px(15) color:UIColor_Hex(0x333333) title:@"上传证件信息".localizedString textAlignment:NSTextAlignmentCenter];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.left.offset(16);
        make.height.offset(40);
    }];
    
    UIImageView *IdCardImageView1 = [[UIImageView alloc] init];
    IdCardImageView1.backgroundColor = UIColor.whiteColor;
    IdCardImageView1.image = [UIImage imageNamed:@"IdCard1"];
    IdCardImageView1.contentMode = UIViewContentModeScaleAspectFit;
    IdCardImageView1.userInteractionEnabled = YES;
    IdCardImageView1.tag = 1001;
    [IdCardImageView1 addTapGesturesWithTarget:self action:@selector(tapIdCardImageView:)];
    [IdCardImageView1 shearRoundedCornersWithRadiu:3];
    [IdCardContentView addSubview:IdCardImageView1];
    [IdCardImageView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.top.equalTo(titleLabel.mas_bottom).offset(10);
        make.height.offset(160);
    }];
    
    UIImageView *IdCardImageView2 = [[UIImageView alloc] init];
    IdCardImageView2.image = [UIImage imageNamed:@"IdCard2"];
    IdCardImageView2.backgroundColor = UIColor.whiteColor;
    IdCardImageView2.contentMode = UIViewContentModeScaleAspectFit;
    IdCardImageView2.userInteractionEnabled = YES;
    IdCardImageView2.tag = 1002;
    [IdCardImageView2 addTapGesturesWithTarget:self action:@selector(tapIdCardImageView:)];
    [IdCardImageView2 shearRoundedCornersWithRadiu:3];
    [IdCardContentView addSubview:IdCardImageView2];
    [IdCardImageView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.top.equalTo(IdCardImageView1.mas_bottom).offset(10);
        make.height.offset(160);
    }];
    
    [IdCardContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.bottom.equalTo(IdCardImageView2.mas_bottom).offset(-10);
        make.top.equalTo(self.IdCradTextField.mas_bottom).offset(10);
    }];
    
    _bottomView = IdCardContentView;
}

- (void)tapIdCardImageView:(UITapGestureRecognizer *)tap {
    
    _imageTag = tap.view.tag;
    _currentImage = (UIImageView *)tap.view;
    
    [self didClickAddButton];
}

- (void)addPassportContentView {
    
    UIView *passportContentView = [UIView tj_addToView:_mainContentView];
    passportContentView.backgroundColor = UIColor_Hex(0xF5F5F5);
    
    UILabel *titleLabel = [UILabel lableWithSuperView:passportContentView font:UIFont_Px(15) color:UIColor_Hex(0x333333) title:@"上传证件信息".localizedString textAlignment:NSTextAlignmentCenter];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.left.offset(16);
        make.height.offset(40);
    }];
    
    UIImageView *passportImageView = [[UIImageView alloc] init];
    passportImageView.backgroundColor = UIColor.whiteColor;
    passportImageView.image = [UIImage imageNamed:@"passport_auth_icon"];
    passportImageView.contentMode = UIViewContentModeScaleAspectFit;
    passportImageView.userInteractionEnabled = YES;
    passportImageView.tag = 1003;
    [passportImageView shearRoundedCornersWithRadiu:3];
    [passportContentView addSubview:passportImageView];
    [passportImageView addTapGesturesWithTarget:self action:@selector(tapIdCardImageView:)];
    [passportImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(16);
        make.right.offset(-16);
        make.top.equalTo(titleLabel.mas_bottom).offset(10);
        make.height.offset(160);
    }];
    
    [passportContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.bottom.equalTo(passportImageView.mas_bottom).offset(-10);
        make.top.equalTo(self.IdCradTextField.mas_bottom).offset(10);
    }];
    
    _bottomView = passportContentView;
}

- (void)didClickAddButton {
    
    TJUIAlertController *alert = [[TJUIAlertController alloc] initWithTitle:@"" message:@"" preferredStyle:QMUIAlertControllerStyleActionSheet];
    [alert addAction:[QMUIAlertAction actionWithTitle:@"取消".localizedString style:QMUIAlertActionStyleCancel handler:nil]];
    [alert addAction:[QMUIAlertAction actionWithTitle:@"相册".localizedString style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:picker animated:YES completion:nil];
        }
    }]];
    
    [alert addAction:[QMUIAlertAction actionWithTitle:@"拍照".localizedString style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        
        AVAuthorizationStatus authStatus =  [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) {
            
            [self alertWithTitle:nil message:@"不能使用相机,前往开启？".localizedString leftButtonName:@"取消".localizedString rightButtonName:@"前往开启".localizedString leftButtonBlock:nil rightButtonBlock:^{
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
            }];
            return;
        }
        [self chooseFromCamera];
        
    }]];
    [alert showWithAnimated:YES];
    
}

#pragma mark - 拍照
- (void)chooseFromCamera {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    } else {
        TJLog(@"不支持拍照功能");
    }
}


//UIimagePickerCotrollerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *newImage = info[UIImagePickerControllerOriginalImage];
    [self uploadImage:newImage];
}


#pragma mark ——— 图片上传
- (void)uploadImage:(UIImage *)image {
    
    
    [TJNetworking.shareNetworking updataImageWithImage:image success:^(NSDictionary * resp, id data) {
        
        self.currentImage.image = image;
        
        if (self.imageTag == 1001) {
            self.IdCardFile1Path = data;
        } else if (self.imageTag == 1002) {
            self.IdCardFile2Path = data;
            
        } else if (self.imageTag == 1003) {
            self.passportFilePath = data;
        }
        [self textFieldDidChange:self.nameTextField];
    } failure:^(NSError *errpr) {
        [TJHud showAutoHideMessage:@"上传失败, 请稍后再试".localizedString];
    }];
}


@end
